#pragma once
#include<iostream>
#include<string>
#include<cstdio>

#include"Log.hpp"
#include"InetAddr.hpp"

class Command 
{
public:
    Command()
    {}
    ~Command()
    {}
    std::string Excute(const std::string &cmdstr)
    {
        std::string result;
        std::cout<<cmdstr<<std::endl;
        FILE *fp=popen(cmdstr.c_str(),"r");
        if(fp)
        {
            char inbuff[1024];
            while(fgets(inbuff,sizeof(inbuff),fp))
            {
                result+=inbuff;
            }
            return result;
        }

        return "excute error";

    }
    void HandlerCommand(int sockfd,InetAddr addr)
    {
        while(true)
        {
            char inbuff[1024];
            ssize_t n=::recv(sockfd,inbuff,sizeof(inbuff)-1,0);
            if(n>0)
            {
                inbuff[n]=0;
                LOG(INFO,"get command from client %s command:%s\n",addr.Ip().c_str(),inbuff);
                std::string result=Excute(inbuff);
                send(sockfd,result.c_str(),result.size(),0);
            }
            else if(n==0)
            {
                LOG(INFO,"client %s quit\n",addr.Ip().c_str());
                break;
            }
            else
            {
                LOG(ERROR,"read error  -%s \n",addr.Ip().c_str());
                break;
            }
        }
    }
};